package com.ezandroid.library.network.http.request;

import android.os.Process;

import java.util.concurrent.BlockingQueue;

/**
 * Provides a thread for performing network dispatch from a queue of requests.
 * <p/>
 * Requests added to the specified queue are processed from the network via a
 * specified {@link Network} interface. Responses are committed to cache, if
 * eligible. Valid responses and
 * errors are posted back to the caller via a {@link ResponseDelivery}.
 */
class Dispatcher extends Thread {
    /**
     * The queue of requests to service.
     */
    private final BlockingQueue<Request<?>> mQueue;
    /**
     * The network interface for processing requests.
     */
    private final Network mNetwork;
    /**
     * For posting responses and errors.
     */
    private final ResponseDelivery mDelivery;
    /**
     * Used for telling us to die.
     */
    private volatile boolean mQuit = false;

    /**
     * Creates a new network dispatcher thread.  You must call {@link #start()}
     * in order to begin processing.
     *
     * @param queue    Queue of incoming requests for triage
     * @param network  Network interface to use for performing requests
     * @param delivery Delivery interface to use for posting responses
     */
    public Dispatcher(BlockingQueue<Request<?>> queue, Network network, ResponseDelivery delivery) {
        mQueue = queue;
        mNetwork = network;
        mDelivery = delivery;
    }

    /**
     * Forces this dispatcher to quit immediately.  If any requests are still in
     * the queue, they are not guaranteed to be processed.
     */
    public void quit() {
        mQuit = true;
        interrupt();
    }

    @Override
    public void run() {
        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
        Request<?> request;
        while (true) {
            // release previous request to avoid leaking request object when mQueue is drained.
            request = null;
            try {
                // Take a request from the queue.
                request = mQueue.take();
            } catch (InterruptedException e) {
                // We may have been interrupted because it was time to quit.
                if (mQuit) {
                    return;
                }
                continue;
            }

            try {
                // If the request was cancelled already, do not perform the network request.
                if (request.isCanceled()) {
                    request.finish();
                    continue;
                }

                // Perform the network request.
                NetworkResponse networkResponse = mNetwork.execute(request);

                // If the server returned 304 AND we delivered a response already,
                // we're done -- don't deliver a second identical response.
                if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                    request.finish();
                    continue;
                }

                // Parse the response here on the worker thread.
                Response<?> response = request.parseNetworkResponse(networkResponse);

                // Post the response back.
                request.markDelivered();
                mDelivery.postResponse(request, response);
            } catch (RequestException requestException) {
                parseAndDeliverNetworkError(request, requestException);
            } catch (Exception e) {
                RequestException requestException = new RequestException(e);
                mDelivery.postError(request, requestException);
            }
        }
    }

    private void parseAndDeliverNetworkError(Request<?> request, RequestException exception) {
        exception = request.parseNetworkError(exception);
        mDelivery.postError(request, exception);
    }
}